<template>
  <div class="department">
    <my-header
      class="department__header"
      :leftText="headerInfo.leftText"
      :title="headerInfo.title"
    ></my-header>

    <div class="department__content">
      <el-tree
        :data="data"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="tree"
        highlight-current
        :props="defaultProps"
      >
      </el-tree>
      <br />
      <van-button type="info" block @click="getCheckedNodes">提交</van-button>
    </div>
  </div>
</template>

<script>
import { queryAllTreeDepts, addDeptUser } from "@/api/dept";
import { queryAllUserDepts } from "@/api/userInfo";
import { Toast } from "vant";
import MyHeader from "@/components/Header";

export default {
  name: "userDepartment",
  components: {
    MyHeader
  },
  data() {
    return {
      changValue:null,
      userId: this.$route.params.id || "",
      headerInfo: {
        leftText: "返回",
        title: "部门信息"
      },
      defaultProps: {
        children: "children",
        label: "deptName"
      },
      data: []
    };
  },
  created() {
    this.getAllTreeDepts();
  },
  mounted() {
    setTimeout(() => {
      //修改数据
      this.changValue = 1;
      //DOM还没更新
      this.$nextTick(() => {
        //DOM现在更新了
        this.initMenus();
      });
    },100);
  },
  methods: {
    // 查部门树
    getAllTreeDepts() {
      queryAllTreeDepts().then((result = []) => {
        this.data = result;
      });
    },
    getCheckedNodes() {
      let checkedNodes = this.$refs.tree.getCheckedNodes(false, true);
      let checkedNodesWithId = [];
      if (checkedNodes.length > 0) {
        checkedNodes.forEach(el => {
          checkedNodesWithId.push({
            userId: this.userId,
            deptId: el.id
          });
        });
        addDeptUser(checkedNodesWithId).then(() => {
          Toast.success("提交成功");
        });
      } else {
        Toast.fail("请选择部门");
      }
    },
    initMenus() {
        queryAllUserDepts(this.userId).then(roleMenus => {
          roleMenus.forEach(item => {
            var node = this.$refs.tree.getNode(item)
            console.info(node)
            if(node&&node.isLeaf){
              this.$refs.tree.setChecked(node,true)
            }
          })
      })
    },
  }
};
</script>

<style lang="scss" scoped>
.department {
  &__content {
    margin-top: 20px;
  }
}
</style>
